package com.gitee.xqxyxchy.swagger;

import java.time.format.DateTimeFormatter;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Configuration extends WebMvcConfigurationSupport {

	private static Logger logger = LoggerFactory.getLogger(Swagger2Configuration.class);
	@Autowired
	@Lazy
	private SwaggerConfig swaggerConfig;
	
	@Bean
    public Docket createRestApi() {
		if(logger.isDebugEnabled()) {
			logger.debug("Starting Swagger");
		}
		logger.info("swaggerConfig ==> {}", swaggerConfig);
		StopWatch watch = new StopWatch();
	    watch.start();
	    
	    Docket docket0 = new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo());
	    
	    String host = swaggerConfig.getHost();
	    if(StringUtils.hasText(host)) {
	    	docket0.host(host);
	    }
	    
	    ApiSelectorBuilder builder = docket0.select();
	    
    	builder.apis(basePackage(swaggerConfig.getBasePackage()));
	    builder.apis(RequestHandlerSelectors.withClassAnnotation(Api.class));
	    builder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
	    if(swaggerConfig.isDisable()){
	    	builder.paths(PathSelectors.none());
	    }else{
	    	builder.paths(PathSelectors.any());
	    }
	    
	    Docket docket = builder.build();
	    watch.stop();
	    if(logger.isDebugEnabled()) {
	    	logger.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
	    }
	    return docket;
    }
	
	/**
     * Predicate that matches RequestHandler with given base package name for the class of the handler method.
     * This predicate includes all request handlers matching the provided basePackage
     *
     * @param basePackage - base package of the classes
     * @return this
     */
    public Predicate<RequestHandler> basePackage(final String basePackage) {
        return new Predicate<RequestHandler>() {
            
            @Override
            public boolean apply(RequestHandler input) {
                return declaringClass(input).transform(handlerPackage(basePackage)).or(true);
            }
        };
    }
    
    /**
     * 处理包路径配置规则,支持多路径扫描匹配以逗号隔开
     * 
     * @param basePackage 扫描包路径
     * @return Function
     */
    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return new Function<Class<?>, Boolean>() {
            
            @Override
            public Boolean apply(Class<?> input) {
                for (String strPackage : basePackage.split(",")) {
                	if(Objects.isNull(input)) {
                		continue;
                	}
                	if(Objects.isNull(input.getPackage())) {
                		continue;
                	}
                	if(!StringUtils.hasText(strPackage)) {
                		continue;
                	}
                    boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                    if (isMatch) {
                        return true;
                    }
                }
                return false;
            }
        };
    }
    
    /**
     * @param input RequestHandler
     * @return Optional
     */
    @SuppressWarnings("deprecation")
	private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
	
	@Bean
    public UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder().validatorUrl("").build();
    }
	
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    private ApiInfo apiInfo() {
    	ApiInfo info = new ApiInfoBuilder()
        		.extensions(swaggerConfig.getExtensions())
                .title(swaggerConfig.getTitle())
                .description(swaggerConfig.getDescription())
                .termsOfServiceUrl(swaggerConfig.getTermsOfServiceUrl())
                .version(swaggerConfig.getVersion())
                .contact(new Contact(swaggerConfig.getContactName(), swaggerConfig.getContactUrl(), swaggerConfig.getContactEmail()))
                .build();
    	return info;
    }
    
	@Value("${spring.jackson.date-format}")
	private String pattern;
	
	@Bean
	public LocalDateTimeSerializer localDateTimeSerializer() {
		return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
	}

}
